﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;


namespace zUpLoad.Common
{
    class cFile
    {
        public static string getFilename(string filter, bool bmultiselect = false)
        {
            OpenFileDialog f = new OpenFileDialog();
            f.FileName = "";
            f.Filter = filter;
            f.Multiselect = bmultiselect;
            DialogResult r = f.ShowDialog();
            if (r == DialogResult.Cancel) { return ""; }
            else { return f.FileName; }
        }
        //获取文件流
        public static byte[] getFileByte(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Open,FileAccess.Read,FileShare.Read);
            BinaryReader r = new BinaryReader(fs);
            r.BaseStream.Seek(0, SeekOrigin.Begin);
            byte[] by = r.ReadBytes(int.Parse(r.BaseStream.Length.ToString()));
            r.Close();
            fs.Close();
            fs.Dispose();
            return by;
            //MemoryStream f = new System.IO.MemoryStream(by);

        }

        //bytes写入文件
        public static void writefile(byte[] bfile, string path)
        {
            try
            {
                FileStream fs = new FileStream(path, FileMode.Create);
                fs.Write(bfile, 0, bfile.Length);
                fs.Close();
            }
            catch (Exception ex)
            { throw new Exception(ex.Message); }
        }

        [DllImport("kernel32.dll")] 
        public static extern IntPtr _lopen(string lpPathName, int iReadWrite);   
        [DllImport("kernel32.dll")] 
        public static extern bool CloseHandle(IntPtr hObject);   
        public const int OF_READWRITE = 2; 
        public const int OF_SHARE_DENY_NONE = 0x40; 
        public static IntPtr HFILE_ERROR = new IntPtr(-1); 
        public static bool fileCanWrite(string filename)
        {
            if (!File.Exists(filename)) { return true ; } 
            bool bRet;
            IntPtr vHandle = _lopen(filename, OF_READWRITE | OF_SHARE_DENY_NONE);
            if (vHandle == cFile.HFILE_ERROR)
            { bRet = false; }
            else
            { bRet = true; }
            CloseHandle(vHandle);
            return bRet;
        }
    }
}
